<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="80px">
        <el-form-item label="计划月">
          <el-select
            v-model="searchParam.planMonth"
            placeholder="请选择计划月"
            clearable
          >
            <el-option label="2024-01" value="2024-01" />
            <el-option label="2024-02" value="2024-02" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称">
          <el-select
            v-model="searchParam.productId"
            placeholder="请选择产品"
            clearable
          >
            <el-option
              v-for="item in productListOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="beforeGetTableList">
            <i-ep-search />
            展示
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="primary" @click="validIsSearched(6)">
          新增物料
        </el-button>
        <el-button
          type="success"
          :disabled="ids.length === 0"
          @click="validIsSearched(4)"
        >
          批量确认
        </el-button>
        <el-button
          type="success"
          :disabled="ids.length === 0"
          @click="validIsSearched(5)"
        >
          批量允许发货
        </el-button>
        <el-button type="primary" @click="validIsSearched(3)">
          导入计划</el-button
        >
        <el-button type="primary" class="ml-3" @click="downLoad">
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <!-- 导入计划 -->
      <ImportExcel ref="weekImportRef" />

      <!-- 合计行的id定义为-999，当表格返回-999时，没有点击事件，展示合计行内容 -->

      <!-- objectSpanMethod方法，objectSpanMethod(param, 3, 7)
      参数3 代表三行合并
      参数13 代表从第13 + 1 列开始取消合并 -->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        element-loading-text="数据准备中，请稍后..."
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :span-method="(param) => objectSpanMethod(param, 3, 13)"
        :header-cell-style="{ textAlign: 'center' }"
        @sort-change="onTableSortChanged"
        class="dataTable"
        :maxHeight="tableHeight"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed
          :selectable="selectableStatus"
        />
        <el-table-column width="70" label="序号" align="center" fixed>
          <template #default="{ $index, row }">
            <span v-if="row.id !== '-999'">{{ $index / 3 + 1 }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          label="产品名称"
          prop="materialCode"
          width="200"
          show-overflow-tooltip
          fixed
          align="left"
          class-name="padding012"
        >
          <template #default="{ row }">
            {{ row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="P/M"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="M/炉"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="生产周期/天"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="期初库存/件"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span
              class="cursor-pointer decoration-underline p-0! can_edit_cell"
              v-if="row.id != -999"
              @click="openEditPrompt(row)"
              >{{ row.dischargeHatchCode }}</span
            >
            <span class="text-[13px]" v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          label="上月废品率"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="本月订单/件"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="期末库存/件"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="黑件生产量/件"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="实时废品率"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="实时库存"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span class="text-[13px]" v-if="row.id != -999">{{
              row.dischargeHatchCode
            }}</span>
            <span class="text-[13px]" v-else>合计</span>
          </template>
        </el-table-column>
        <el-table-column label="大项" width="90" align="center">
          <template #default="{ $index }">
            <span class="text-[13px]" v-if="($index + 1) % 3 == 1"
              >要货数量</span
            >
            <span class="text-[13px]" v-if="($index + 1) % 3 == 2"
              >计划模数</span
            >
            <span class="text-[13px]" v-if="($index + 1) % 3 == 0"
              >完成数量</span
            >
          </template>
        </el-table-column>
        <el-table-column
          v-for="(dayItem, dayIndex) in intervalDayList"
          :key="dayIndex"
          :label="`${dayItem.date}\n${dayItem.week}`"
          :label-class-name="
            dayItem.week == 0 || dayItem.week == 6 ? 'bg-free' : ''
          "
          min-width="65"
          align="right"
        >
          <template #default="{ row, $index }">
            <div
              :style="{
                backgroundColor:
                  inConsistent(row, $index, dayIndex) == ''
                    ? ''
                    : inConsistent(row, $index, dayIndex),
              }"
            >
              <!-- 计划数量 -->
              <div v-if="($index + 1) % 3 == 1">
                <span
                  v-if="row.id !== '-999'"
                  class="cursor-pointer cellNumber"
                  @click="openAddGoods(row.scheduleList[dayIndex])"
                  >{{ row.scheduleList[dayIndex]?.demandQuantity }}</span
                >
                <span v-else>
                  {{ row.scheduleList[dayIndex]?.demandQuantity }}
                </span>
              </div>
              <!-- 计划模数 -->
              <div v-if="($index + 1) % 3 == 2">
                <span
                  v-if="row.id !== '-999'"
                  class="cursor-pointer cellNumber"
                  @click="
                    openFeedbackInfo(
                      row.feedbackList[dayIndex].id,
                      '计划信息',
                      row.feedbackList[dayIndex]?.demandStatus,
                      row.feedbackList[dayIndex]?.demandQuantity
                    )
                  "
                  >{{ row.feedbackList[dayIndex]?.feedbackTotal || "" }}</span
                >
                <span v-else>
                  {{ row.feedbackList[dayIndex]?.feedbackTotal }}
                </span>
              </div>
              <!-- 确认数量 -->
              <div v-if="($index + 1) % 3 == 0">
                <span
                  v-if="row.id !== '-999'"
                  class="cursor-pointer cellNumber"
                  @click="
                    openFeedbackInfo(
                      row.scheduleList[dayIndex].id,
                      '完成信息',
                      row.scheduleList[dayIndex]?.demandStatus
                    )
                  "
                  >{{ row.scheduleList[dayIndex]?.confirmQuantity || "" }}</span
                >
                <span v-else>
                  {{ row.scheduleList[dayIndex]?.confirmQuantity }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增物料弹窗 -->
    <demo-purchase-demand-add-dialog
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :endDate="addGoodsDialog.endDate"
      :beginDate="addGoodsDialog.beginDate"
      @reset-table="getTableList(0)"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 新增物料(新版)弹窗 -->
    <demo-goods-add-new-dialog
      :visible="addNewDialog.visible"
      :title="addNewDialog.title"
      :endDate="addNewDialog.endDate"
      :beginDate="addNewDialog.beginDate"
      :data="addNewDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 新增要货 -->
    <demo-require-goods-add-dialog
      :visible="addGoodsDialog.visible"
      :title="addGoodsDialog.title"
      :id="addGoodsDialog.id"
      :cellId="addGoodsDialog.cellId"
      :endDate="addGoodsDialog.endDate"
      :beginDate="addGoodsDialog.beginDate"
      :data="addGoodsDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="addGoodsDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 反馈信息确认弹窗 -->
    <demo-feedback-info-dialog
      :visible="feedbackDialog.visible"
      :title="feedbackDialog.title"
      :cellId="feedbackDialog.cellId"
      :demandStatus="feedbackDialog.demandStatus"
      :endDate="feedbackDialog.endDate"
      :begirate="feedbackDialog.beginDate"
      :data="feedbackDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="feedbackDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table ref="uploadErrorRef" :errorDataList="errorDataList" />
  </div>
</template>

<script setup lang="ts">
import {
  SearchInterface,
  TableResultObject,
  ScheduleList,
} from "./utilejs/interface";
import {
  resolveSearchData,
  objectSpanMethod,
  getDaysByMonth,
  selectableStatus,
  inConsistent,
} from "./utilejs/index";
import { mockTableList, mockTableList1 } from "./utilejs/mock";
import { filterOrder, promptValidateNumber } from "@/utils/commonHooks";
import dayjs from "dayjs";
import request from "@/utils/request";
import {
  useDownload,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";

defineOptions({
  name: "DEMOSRMPURCHASEDEMAND",
  inheritAttrs: false,
});

// 表格固定高度
const tableHeight = ref<any>("auto");
onMounted(() => {
  // 计算表格高度
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
    console.log("tableHeight.value", tableHeight.value);
  }, 0);
});
// 初始化搜索参数数据
const searchParam = reactive<SearchInterface>({
  productId: "",
  planMonth: "",
});

// 点击搜索按钮后被保存的搜索数据
const searchedParam = reactive<SearchInterface>({
  productId: "",
  planMonth: "",
});

const productListOptions = [
  {
    value: "1",
    label: "产品1",
  },
  {
    value: "2",
    label: "产品2",
  },
  {
    value: "3",
    label: "产品3",
  },
];

// 搜索时间变化后处理函数
const intervalDayList = ref<any[]>([]);

// 行复选框选中后处理
const ids = ref<string[]>([]);
const dataTableRef = ref();
function handleSelectionChange(selection: TableResultObject[]) {
  ids.value = selection.map((item: TableResultObject) => item.id);
}

// 开始展示逻辑处理
const loading = ref(false);
const tableData = ref([]);
// 点击展示之前
function beforeGetTableList() {
  if (!searchParam.planMonth) {
    ElMessage.error("请选择计划月");
    return;
  }
  getTableList(1);
}

// 点击展示之后
async function getTableList(isReset = 0) {
  // isReset为 1 加载刷新、0 无感知刷新
  if (isReset === 1) {
    dataTableRef.value.setScrollTop(0);
    loading.value = true;
  }
  const { data }: any = await request({
    url: "/srm/srmmaterialdemand/getDetailByPeriod",
    method: "post",
    data: isReset === 0 ? toRaw(searchedParam) : toRaw(searchParam),
  }).catch(() => {
    //以下为模拟数据，待真实接口后，可删除

    // 储存被搜索条件
    Object.assign(searchedParam, {
      ...toRaw(searchParam),
    });
    // 时间处理
    intervalDayList.value = getDaysByMonth(searchParam.planMonth);
    // 数据处理
    tableData.value = resolveSearchData(mockTableList);

    loading.value = false;
  });
  // 储存被搜索条件
  Object.assign(searchedParam, {
    ...toRaw(searchParam),
  });
  // 时间处理
  intervalDayList.value = getDaysByMonth(searchParam.planMonth);
  // 数据处理
  tableData.value = resolveSearchData(data);
  loading.value = false;
}

// 监听表格后台排序方法
const initParam = reactive({ sort: {} });
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };

  getTableList(1);
}

// 新增物料弹窗及操作逻辑
const addDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
function changeVisible(value: boolean) {
  addDialog.visible = value;
  addGoodsDialog.visible = value;
  feedbackDialog.visible = value;
  addNewDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    addGoodsDialog.data = {};
    addGoodsDialog.cellId = "";
    addGoodsDialog.id = "";
    feedbackDialog.data = {};
    feedbackDialog.cellId = "";
    addNewDialog.data = {};
  }
}

// 新增要货弹窗及操作逻辑
const addGoodsDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  id: "",
});
const openAddGoods = (cellRow?: ScheduleList) => {
  const cellId = cellRow?.id || "";
  let title = "";
  if (cellRow?.demandStatus == 3) {
    title = "查看要货详情";
  } else {
    title = !cellId ? "新增要货" : "修改要货";
  }
  const object = {
    visible: true,
    title: title,
    readvisible: cellRow?.demandStatus == 3 ? true : false,
    beginDate: !cellId
      ? dayjs(searchedParam.planMonth).startOf("month").format("YYYY-MM-DD")
      : "",
    endDate: !cellId
      ? dayjs(searchedParam.planMonth).endOf("month").format("YYYY-MM-DD")
      : "",
    id: !cellId ? ids.value[0] : "",
    cellId: cellId,
  };
  Object.assign(addGoodsDialog, { ...object });
  console.log("addGoodsDialog", addGoodsDialog);
};

// 反馈信息确认弹窗及操作逻辑
const feedbackDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  demandStatus: null,
});
const openFeedbackInfo = (
  cellId = "",
  title = "",
  demandStatus = null,
  contentNumber = null
) => {
  console.log(demandStatus, contentNumber);

  const object = {
    visible: true,
    title: title,
    beginDate: dayjs(searchedParam.planMonth)
      .startOf("month")
      .format("YYYY-MM-DD"),
    endDate: dayjs(searchedParam.planMonth).endOf("month").format("YYYY-MM-DD"),
    cellId: cellId,
    demandStatus: demandStatus,
    contentNumber: contentNumber == null ? "" : contentNumber,
  };
  Object.assign(feedbackDialog, { ...object });
};

// 操作前校验是否搜索过
function validIsSearched(type: number) {
  if (!searchedParam.planMonth) {
    ElMessage.error("请先选择计划月后，再进行操作");
    return;
  } else {
    // 导入计划
    if (type === 3) {
      weekBatchImport();
    }

    // 批量确认
    if (type === 4) {
      confirmBatch();
    }

    // 批量允许发货
    if (type === 5) {
      sendAbleBatch();
    }

    // 新增物料(新版)
    if (type === 6) {
      openAddMaterialNew();
    }
  }
}

// 导入计划
const weekImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
async function weekImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/srm/srmmaterialdemand/upload", formdata, config)
    .then((res: any) => {
      weekImportRef.value.resCode = res.code;
      if (res.code === 300) {
        errorDataList.value = res.data;
        uploadErrorRef.value.errorBox = true;
      }
    })
    .catch((e) => {
      weekImportRef.value.resCode = 500;
    });
}
const weekBatchImport = () => {
  let params = {
    title: "导入计划",
    tempApi: "", //模板下载
    importApi: weekImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {
      planMonth: searchedParam.planMonth,
    },
  };
  weekImportRef.value.acceptParams(params);
};

// 导出
const downLoad = () => {
  if (!searchedParam.planMonth) {
    ElMessage.error("请先选择计划月后，再进行操作");
    return;
  } else {
    useDownload(
      "/srm/srmmaterialdemand/export",
      "采购需求",
      searchParam,
      true,
      ".xls"
    );
  }
};

function confirmBatch() {
  ElMessageBox.confirm("请确认，是否继续批量确认操作?", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 全部反馈接口加载成功
        instance.confirmButtonLoading = true;
        const res: any = await request({
          url: "/srm/srmdemandschedule/confirmBatch",
          method: "post",
          data: {
            planMonth: searchedParam.planMonth,
            ids: ids.value,
          },
        }).catch(() => {
          instance.confirmButtonLoading = false;
          done();
        });
        if (res?.code === 200) {
          ElMessage.success("批量确认成功");
          getTableList(1);
        }
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
  })
    .then(() => {})
    .catch(() => {});
}

function sendAbleBatch() {
  ElMessageBox.confirm("请确认，是否继续批量允许发货操作?", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 全部反馈接口加载成功
        instance.confirmButtonLoading = true;
        const res: any = await request({
          url: "/srm/srmdemandschedule/sendAbleBatch",
          method: "post",
          data: {
            planMonth: searchedParam.planMonth,
            ids: ids.value,
          },
        }).catch(() => {
          instance.confirmButtonLoading = false;
          done();
        });
        if (res?.code === 200) {
          ElMessage.success("批量允许发货成功");
          getTableList(1);
        }
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
  })
    .then(() => {})
    .catch(() => {});
}
// 新增物料（新版）弹窗及操作逻辑
const addNewDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
});
const openAddMaterialNew = () => {
  const object = {
    visible: true,
    title: "新增物料",
    beginDate: dayjs(searchedParam.planMonth)
      .startOf("month")
      .format("YYYY-MM-DD"),
    endDate: dayjs(searchedParam.planMonth).endOf("month").format("YYYY-MM-DD"),
  };
  Object.assign(addNewDialog, { ...object });
};

const openEditPrompt = (row: any) => {
  ElMessageBox.prompt("期初库存（件）", row.materialName, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    customClass: "prompt_custom",
    closeOnClickModal: false,
    inputValue: row.dischargeHatchCode,
    inputValidator: (value: string) => promptValidateNumber(value),
  })
    .then(({ value }) => {
      console.log("携带参数，进行接口请求", row.id, value);
      ElMessage({
        type: "success",
        message: `修改成功`,
      });
      getTableList(1);
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
// 所有表格样式
:deep(.dataTable) {
  .el-table__body td.el-table__cell {
    padding: 0;
    .can_edit_cell:hover {
      color: #409eff !important;
    }
  }
  .cell {
    padding: 0;
    white-space: pre-wrap;
  }
  .padding012 .cell {
    padding: 0 12px !important;
  }
  td.el-table__cell .cell > :first-child {
    padding: 3px 12px;
  }

  .seltAllbtnDis .cell {
    visibility: hidden;
  }
  .el-table__empty-block {
    height: 120px !important;
  }
}

:deep(.el-table--border th.bg-free) {
  background-color: rgb(239.8, 248.9, 235.3) !important;
}

// 红色标识
.c-red-font {
  background-color: #fef1f1 !important;
  span {
    // color: lightcoral;
    color: brown !important;
  }
}

// 绿色标识
.c-green {
  background: #55efc4 !important;
  span {
    color: #2f4f4f !important;
  }
}

.cellNumber:hover {
  text-decoration: underline;
}
</style>
